package pl.mchaniewski.ryneczek.web.user;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.servlet.http.Cookie;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.pojo.User;
import pl.mchaniewski.ryneczek.services.UserService;
import pl.mchaniewski.ryneczek.utilities.CookieUtil;
import pl.mchaniewski.ryneczek.utilities.DateUtil;
import pl.mchaniewski.ryneczek.utilities.FacesMessageUtil;
import pl.mchaniewski.ryneczek.utilities.I18nUtil;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;
import pl.mchaniewski.ryneczek.utilities.SecurityUtil;

@Component
@Scope("session")
public class UserInfoBean {
    private UserService userService;
    private boolean helpNeeded;

    /* PostConstruct parameters */
    private User user;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String getLogin() {
        return user.getLogin();
    }

    public String getLastLogin() {
        return DateUtil.dateToString(user.getLastLogin());
    }

    public String getCreateDate() {
        return DateUtil.dateToString(user.getCreateDate());
    }

    @PostConstruct
    public void init() {
        UserDetails userSecurity = SecurityUtil.getUserDetails();
        if (userSecurity != null) {
            String loggedUsername = userSecurity.getUsername();
            user = userService.findByLogin(loggedUsername);
        }
    }

    private void setHelpNeeded(String value) {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("maxAge", CookieUtil.COOKIE_MAX_AGE);
        properties.put("path", "/");
        CookieUtil.addCookie("helpNeeded", value, properties);
        helpNeeded = Boolean.valueOf(value);
    }

    public boolean isHelpNeeded() {
        Cookie cookie = CookieUtil.getCookie("helpNeeded");

        if (cookie != null) {
            helpNeeded = Boolean.valueOf(cookie.getValue());
        } else {
            setHelpNeeded("true");
        }

        return helpNeeded;
    }

    public String turnOnHelpers() {
        setHelpNeeded("true");

        FacesMessageUtil.addMessage(
                I18nUtil.getLocalizedMessage("userinfobean.helperson"),
                FacesMessage.SEVERITY_INFO);

        return NavigationUtil.SAME_PAGE;
    }

    public String turnOffHelpers() {
        setHelpNeeded("false");

        FacesMessageUtil.addMessage(
                I18nUtil.getLocalizedMessage("userinfobean.helpersoff"),
                FacesMessage.SEVERITY_INFO);

        return NavigationUtil.SAME_PAGE;
    }

}
